package com.css.fxfzypg.modules.similitudeAnalyse.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.service.SettingSeismicService;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.auxiliaryDecision.service.AuxiliaryDecisionService;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.paramSetting.entity.ParamSettingVO;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.paramSetting.service.ParamSettingService;
import com.css.fxfzypg.modules.baseData.entity.HisPrEntity;
import com.css.fxfzypg.modules.baseData.service.EarthquakeDisasterService;
import com.css.fxfzypg.modules.baseData.service.HisprService;
import com.css.fxfzypg.modules.baseData.service.KangZhenTuService;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SeismicInfluenceflyPbe;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SettingSeismicInfluenceflied;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.SettingSeismicInfluencefliedRepository;
import com.css.fxfzypg.modules.model.entity.IntensityAttenuation;
import com.css.fxfzypg.modules.model.service.IntensityAttenuationService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.ReportManagement;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportManagementService;
import com.css.fxfzypg.modules.similitudeAnalyse.consts.AreaConsts;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.*;
import com.css.fxfzypg.modules.similitudeAnalyse.param.QueParams1;
import com.css.fxfzypg.modules.similitudeAnalyse.repository.HisEarDamResultRepository;
import com.css.fxfzypg.modules.similitudeAnalyse.repository.SimAnalyseRepository;
import com.css.fxfzypg.modules.similitudeAnalyse.service.SimAnalyseService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.ListUtil;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.Xml2ObjectUtil;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SimAnalyseServiceImpl implements SimAnalyseService {
    @Resource
    private SetEarthquakeMapService setEarthquakeMapService;
    @Resource
    private HisprService hisprService;
    @Resource
    private EarthquakeDisasterService earthquakeDisasterService;
    @Resource
    private KangZhenTuService kangZhenTuService;
    @Resource
    private ParamSettingService paramSettingService;
    @Resource
    private SimAnalyseRepository simAnalyseRepository;
    @Resource
    IntensityAttenuationService intensityAttenuationService;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    SettingSeismicService settingSeismicService;
    @Resource
    SettingSeismicInfluencefliedRepository SettingSeismicInfluencefliedRepository;

    @Resource
    PreAssessTaskService preAssessTaskService;

    @Resource
    ReportManagementService reportManagementService;

    @Resource
    HisEarDamResultRepository hisEarDamResultRepository;
    @Resource
    AuxiliaryDecisionService auxiliaryDecisionService;

    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    RestTemplate restTemplate;
    @Value("${basicData.url1}")
    String basicDataUrl1;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void similitudeAnalyse(List<RealEarthquakeEntity> realEarthquakeEntities) throws ParseException {
        for (RealEarthquakeEntity item : realEarthquakeEntities) {
            List<String> provinceInfo = setEarthquakeMapService.queryProvinceByLonLat(item.getEpiLon(), item.getEpiLat());
            if (provinceInfo.size() <= 0) {
                continue;
            }
            String provinceName = provinceInfo.get(1);
            //判断是否是东部
            boolean eastFlag = ListUtil.useList(AreaConsts.EAST, provinceName);
            //判断是否是西部
            boolean westFlag = ListUtil.useList(AreaConsts.WEST, provinceName);
            //获取计算参数
            ParamSettingVO params = paramSettingService.getParamSetting();
            //假数据测试
            if ("河北邢台市沙河市".equals(item.getLocationC())) {
                item.setM("6.3");
                item.setEpiLon("106.5");
                item.setEpiLat("29.54");
            }


            if (eastFlag || westFlag) {
                //是东部   判断震级是否大于4
                if (eastFlag) {
                    if (AreaConsts.compare(new Double(item.getM()), AreaConsts.EAST_MAGNITUDE)) {
                        //获取实际发生地震震中位置所在区县有设定地震的或在O（默认50）公里范围内有设定地震的数据

                        List<HisPrEntity> list = hisprService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), new BigDecimal(params.getO()).multiply(BigDecimal.valueOf(1000)), item.getM());

                        //List<SetSeiPointVo> setSeiPointVoList = settingSeismicService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), params.getO(), item.getM());
                        //筛选出震级差 |设定地震震级-实际地震震级|<=0.3的数据并去重
                        //List<SetSeiPointVo> list = dataWinnow(setSeiPointVoList, new BigDecimal(item.getM()));
                        similarityAnalysis(item, list, params, provinceName);
                    } else {
                        continue;
                    }
                }
                //是西部   判断震级是否大于5
                if (westFlag) {
                    if (AreaConsts.compare(new Double(item.getM()), AreaConsts.WEST_MAGNITUD)) {
                        //获取实际发生地震震中位置所在区县有设定地震的或在O（默认50）公里范围内有设定地震的数据
                        List<HisPrEntity> list = hisprService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), new BigDecimal(params.getO()).multiply(BigDecimal.valueOf(1000)), item.getM());

                        //List<SetSeiPointVo> setSeiPointVoList = settingSeismicService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), params.getO(), item.getM());
                        //筛选出震级差 |设定地震震级-实际地震震级|<=0.3的数据并去重
                        /*List<SetSeiPointVo> list = dataWinnow(setSeiPointVoList, new BigDecimal(item.getM()));*/
                        similarityAnalysis(item, list, params, provinceName);
                    } else {
                        continue;
                    }
                }

            }
        }
    }

    private void similarityAnalysis(RealEarthquakeEntity realEarthquakeEntity, List<HisPrEntity> list,
                                    ParamSettingVO params, String provinceName) throws ParseException {
        simAnalyseRepository.deleteAllData();
        for (HisPrEntity item : list) {
            String epiLon = realEarthquakeEntity.getEpiLon();
            String epiLat = realEarthquakeEntity.getEpiLat();
            BigDecimal longitude = item.getDhpEpicenterLongitude();
            BigDecimal latitude = item.getDhpEpicenterLatitude();
            Double setLon = longitude.doubleValue();
            Double setLat = latitude.doubleValue();
            Double realLon = new Double(epiLon);
            Double realLat = new Double(epiLat);
            String distance = DistanceUtils.getDistance(setLon, setLat, realLon, realLat);
            BigDecimal kilRange = new BigDecimal(params.getO());
            BigDecimal kilDistance = new BigDecimal(distance);
            //震中距离指标
            BigDecimal f1 = (kilRange.subtract(kilDistance)).divide(kilRange).setScale(2, BigDecimal.ROUND_HALF_UP);

            //房屋总栋数指标
            int reaHouTotal = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, false);
            int setHouTotal = kangZhenTuService.getHouseTotalByLonAndLat(longitude.toString(), latitude.toString(), false);
            BigDecimal reaHouDecimal = new BigDecimal(Integer.toString(reaHouTotal));
            BigDecimal setHouDecimal = new BigDecimal(Integer.toString(setHouTotal));
            BigDecimal discuss = new BigDecimal("0");
            if (!(reaHouDecimal.compareTo(new BigDecimal("0")) == 0)) {
                discuss = (reaHouDecimal.subtract(setHouDecimal)).abs().divide(reaHouDecimal, 6, BigDecimal.ROUND_HALF_UP);
            }

            BigDecimal p1 = new BigDecimal("1").subtract(discuss).setScale(2, BigDecimal.ROUND_HALF_UP);

            //疑似抗震能力严重不足房屋总栋数指标
            int reaHouTotal1 = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, true);
          //  int setHouTotal1 = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, true);
            int setHouTotal1 = kangZhenTuService.getHouseTotalByLonAndLat(longitude.toString(), latitude.toString(), true);
            BigDecimal reaHouDecimal1 = new BigDecimal(Integer.toString(reaHouTotal1));
            BigDecimal setHouDecimal1 = new BigDecimal(Integer.toString(setHouTotal1));
            BigDecimal discuss1 = new BigDecimal("0");
            if (!(reaHouDecimal1.compareTo(new BigDecimal("0")) == 0)) {
                discuss1 = (reaHouDecimal1.subtract(setHouDecimal1)).abs().divide(reaHouDecimal1, 6, BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal p2 = new BigDecimal("1").subtract(discuss1).setScale(2, BigDecimal.ROUND_HALF_UP);


            //房屋抗震能力指标
            BigDecimal f2 = p1.multiply(new BigDecimal(params.getD1()).movePointLeft(2)).add(p2.multiply(new BigDecimal(params.getD2()).movePointLeft(2)));

            //震级指标
            BigDecimal f3 = new BigDecimal("1").subtract((item.getDhpMagnitude().subtract(new BigDecimal(realEarthquakeEntity.getM())).abs()).divide(new BigDecimal(0.3), 2, BigDecimal.ROUND_HALF_UP));


            //相似性计算结果
            BigDecimal w1 = new BigDecimal(params.getW1()).movePointLeft(2);
            BigDecimal w2 = new BigDecimal(params.getW2()).movePointLeft(2);
            BigDecimal w3 = new BigDecimal(params.getW3()).movePointLeft(2);

            BigDecimal simResults = f1.multiply(w1).add(f2.multiply(w2).add(f3.multiply(w3))).setScale(2, BigDecimal.ROUND_HALF_UP);

            SimAnaResult simAnaResult = new SimAnaResult();

            //数据保存
            simAnaResult.setId(UUIDGenerator.getUUID());
            simAnaResult.setRealEarthquakeLevel(new BigDecimal(realEarthquakeEntity.getM()));
            simAnaResult.setRealLongitude(new BigDecimal(realEarthquakeEntity.getEpiLon()));
            simAnaResult.setRealLatitude(new BigDecimal(realEarthquakeEntity.getEpiLat()));
            simAnaResult.setRealDepth(realEarthquakeEntity.getEpiDepth());
            simAnaResult.setRealLocation(realEarthquakeEntity.getLocationC());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simAnaResult.setRealTime(sdf.parse(realEarthquakeEntity.getOTime()));
            simAnaResult.setHisPrId(item.getId());
            simAnaResult.setDistanceTarget(f1);
            simAnaResult.setDistance(distance);
            simAnaResult.setSeismicCapacityTarget(f2);
            simAnaResult.setRealHouseTotal(Integer.toString(reaHouTotal));
            simAnaResult.setHouseTotal(Integer.toString(setHouTotal));
            simAnaResult.setRealDearthHouseTotal(Integer.toString(setHouTotal1));
            simAnaResult.setDearthHouseTotal(Integer.toString(setHouTotal1));
            simAnaResult.setEarthquakeLevelTarget(f3);
            simAnaResult.setSimilarityCalculationResult(simResults);
            simAnaResult.setCataId(realEarthquakeEntity.getCataId());
            simAnaResult.setProvinceName(provinceName);
            simAnalyseRepository.save(simAnaResult);

        }
    }

    /**
     * 获取数据地址
     */
    private static final String URL = "http://1.eqweixin.sinaapp.com/zxml.php";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse similitudeAnalyse1() {
        String cataId = "";
        try {
            //调取接口 返回真实数据对象
            List<RealEarthquakeEntity> realEarthquakeEntities = Xml2ObjectUtil.getRealEarthquakeEntity(URL);
            if (realEarthquakeEntities == null || realEarthquakeEntities.size() == 0) {
                return RestResponse.fail("=====该时间:{}" + PlatformDateUtils.getCurrentTimestamp() + "的数据为空");
            }
            List<RealEarthquakeEntity> collect = realEarthquakeEntities.stream().sorted(Comparator.comparing(RealEarthquakeEntity::getOTime,
                    Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());
            RealEarthquakeEntity item = collect.get(collect.size() - 1);

            cataId = item.getCataId();
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(cataId))) {
                return RestResponse.fail("该线程中的该数据:{}" + cataId + "正在被计算！");
            }
            redisTemplate.opsForValue().set(cataId, "1", 10L, TimeUnit.SECONDS);

            RealEarthquakeEntity realEarthquakeEntity = simAnalyseRepository.getById(cataId);
            if (realEarthquakeEntity != null) {
                return RestResponse.fail("该数据:{}" + cataId + "已经被计算！");
            }

            String s = setEarthquakeMapService.queryProvinceCityCountyNameStringByLonLat(item.getEpiLon(), item.getEpiLat());
            if (PlatformObjectUtils.isEmpty(s)) {
                return RestResponse.fail("未获取到当前数据:{}" + cataId + "经纬度的省份！");
            }
            String[] split = s.split(",");
            //省名称
            item.setProvince(split[0]);
            //市名称
            item.setCity(split[1]);
            //县名称
            item.setCounty(split[2]);
            //空间数据
            item.setGeom("POINT("+item.getEpiLon()+" "+item.getEpiLat()+")");
            // simAnalyseRepository.saveRealEarthquake(item);

            String provinceName = split[0];
            //判断是否是东部
            boolean eastFlag = ListUtil.useList(AreaConsts.EAST, provinceName);
            //判断是否是西部
            boolean westFlag = ListUtil.useList(AreaConsts.WEST, provinceName);
            //获取计算参数
            ParamSettingVO params = paramSettingService.getParamSetting();
            //是东部   判断震级是否大于4
            //是西部   判断震级是否大于5
            if ((eastFlag && AreaConsts.compare(new Double(item.getM()), AreaConsts.EAST_MAGNITUDE)) || (westFlag && AreaConsts.compare(new Double(item.getM()), AreaConsts.WEST_MAGNITUD))) {
                //震后辅助决策
                auxiliaryDecisionService.writeData(item);

                //历史预评估结果数据
                //获取实际发生地震震中位置所在区县有设定地震的或在O（默认50）公里范围内有设定地震的数据
                List<HisPrEntity> list1 = hisprService.getDataByLongitudeAndLatitude(item.getEpiLon(),
                        item.getEpiLat(), new BigDecimal(params.getO()).multiply(BigDecimal.valueOf(1000)), item.getM());
                // List<SetSeiPointVo> setSeiPointVoList = settingSeismicService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), params.getO(), item.getM());
                //筛选出震级差 |设定地震震级-实际地震震级|<=0.3的数据并去重
                // List<HisPrEntity> newList = dataWinnow(list1, new BigDecimal(item.getM()));
                if (list1 != null && list1.size()>0){
                    RestResponse restResponse = similarityAnalysis1(item, list1, params);
                    if (restResponse.getCode() != 200) {
                        return RestResponse.fail(restResponse.getMessage());
                    }
                }

                //历史地震灾害数据
                boolean boo = save(new BigDecimal(params.getU()).multiply(BigDecimal.valueOf(1000)), item.getM(), item);
                if (!boo){
                    simAnalyseRepository.delRealEarthquake(cataId);
                    return RestResponse.fail("历史地震灾害数据保存失败！");
                }

            } else {
                return RestResponse.fail("当前数据:{}" + cataId + "未满足震级大于等于东部地区4级、西部地区5级！");
            }
            // List<KangZhenTu> byGeom = kangZhenTuService.getByGeom(influenceEllipse);
        } catch (Exception e) {
            e.printStackTrace();
            simAnalyseRepository.delRealEarthquake(cataId);
            return RestResponse.fail("分析并保存失败！");
        } finally {
            if (PlatformObjectUtils.isNotEmpty(cataId)) {
                redisTemplate.delete(cataId);
            }
        }
        return RestResponse.succeed("分析并保存成功！");
    }

    private RestResponse similarityAnalysis1(RealEarthquakeEntity realEarthquakeEntity, List<HisPrEntity> list,
                                             ParamSettingVO params) throws ParseException, UnsupportedEncodingException {
        //simAnalyseRepository.deleteAllData();

        RestResponse restResponse = realSeismicInfluenceflied(realEarthquakeEntity);
        if (restResponse.getCode() != 200) {
            return restResponse;
        }
        String epiLon = realEarthquakeEntity.getEpiLon();
        String epiLat = realEarthquakeEntity.getEpiLat();

        boolean tab = false;
        RealSeismicInfluenceflyPbe influenceflied = (RealSeismicInfluenceflyPbe) restResponse.getData();
        for (HisPrEntity item : list) {
            BigDecimal longitude = item.getDhpEpicenterLongitude();
            BigDecimal latitude = item.getDhpEpicenterLatitude();
            String faultAngle = setEarthquakeMapService.getClosestFaultageAngleByLonLat(longitude.toString(),
                    latitude.toString());//最近切线角度

            List<SettingSeismicDetails> seismicDetailsList = settingSeismicService.getByTaskNumAndLonAndLatAndEqLevel(item.getDhpTaskNum(), longitude, latitude,
                    item.getDhpMagnitude());
            if (seismicDetailsList.size() < 1) {
                continue;
                // return RestResponse.fail("该历史预评估数据:{}" + item.getId() + "没有与之对应的设定地震!");
            }
            SeismicInfluenceflyPbe influenceflied1 = null;
            List<SettingSeismicDetails> collect = seismicDetailsList.stream().filter(i -> faultAngle.equals(String.valueOf(i.getFaultTangentAngle()))).collect(Collectors.toList());
            if (collect.size() > 0) {
                influenceflied1 = SettingSeismicInfluencefliedRepository.getByDetailsId(collect.get(0).getId());
            } else {
                influenceflied1 = settingSeismicInfluenceflied(seismicDetailsList.get(0));
            }
            if (influenceflied1 == null) {
                continue;
            }

            String distance = DistanceUtils.getDistance(longitude.doubleValue(), latitude.doubleValue(), new Double(epiLon), new Double(epiLat));
            BigDecimal kilRange = new BigDecimal(params.getO());
            //震中距离指标
            BigDecimal f1 = (kilRange.subtract(new BigDecimal(distance))).divide(kilRange, 2, BigDecimal.ROUND_HALF_UP);

            //房屋总栋数指标
            int reaHouTotal = kangZhenTuService.getByGeom(influenceflied.getGeom(), false);
            // int reaHouTotal = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, false);
            int setHouTotal = kangZhenTuService.getByGeom(influenceflied1.getGeom(), false);
            // int setHouTotal = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, false);
            BigDecimal reaHouDecimal = BigDecimal.valueOf(reaHouTotal);
            BigDecimal setHouDecimal = BigDecimal.valueOf(setHouTotal);
            BigDecimal discuss = BigDecimal.ZERO;
            if (!(reaHouDecimal.compareTo(BigDecimal.ZERO) == 0)) {
                discuss = (reaHouDecimal.subtract(setHouDecimal)).abs().divide(reaHouDecimal, 6, BigDecimal.ROUND_HALF_UP);
            }

            BigDecimal p1 = BigDecimal.ONE.subtract(discuss).setScale(2, RoundingMode.HALF_UP);

            //疑似抗震能力严重不足房屋总栋数指标
            int reaHouTotal1 = kangZhenTuService.getByGeom(influenceflied.getGeom(), true);
            // int reaHouTotal1 = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, true);
            int setHouTotal1 = kangZhenTuService.getByGeom(influenceflied1.getGeom(), true);
            // int setHouTotal1 = kangZhenTuService.getHouseTotalByLonAndLat(epiLon, epiLat, true);
            BigDecimal reaHouDecimal1 = BigDecimal.valueOf(reaHouTotal1);
            BigDecimal setHouDecimal1 = BigDecimal.valueOf(setHouTotal1);
            BigDecimal discuss1 = BigDecimal.ZERO;
            if (!(reaHouDecimal1.compareTo(BigDecimal.ZERO) == 0)) {
                discuss1 = (reaHouDecimal1.subtract(setHouDecimal1)).abs().divide(reaHouDecimal1, 6, BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal p2 = BigDecimal.ONE.subtract(discuss1).setScale(2, RoundingMode.HALF_UP);


            //房屋抗震能力指标
            BigDecimal f2 = p1.multiply(new BigDecimal(params.getD1()).movePointLeft(2)).add(p2.multiply(new BigDecimal(params.getD2()).movePointLeft(2)));

            //震级指标
            BigDecimal f3 =
                    BigDecimal.ONE.subtract((item.getDhpMagnitude().subtract(new BigDecimal(realEarthquakeEntity.getM())).abs()).divide(new BigDecimal(0.3), 2, BigDecimal.ROUND_HALF_UP));


            //相似性计算结果
            BigDecimal w1 = new BigDecimal(params.getW1()).movePointLeft(2);
            BigDecimal w2 = new BigDecimal(params.getW2()).movePointLeft(2);
            BigDecimal w3 = new BigDecimal(params.getW3()).movePointLeft(2);

            BigDecimal simResults = f1.multiply(w1).add(f2.multiply(w2).add(f3.multiply(w3))).setScale(2, BigDecimal.ROUND_HALF_UP);

            SimAnaResult simAnaResult = new SimAnaResult();

            //数据保存
            simAnaResult.setId(UUIDGenerator.getUUID());
            simAnaResult.setCataId(realEarthquakeEntity.getCataId());
            simAnaResult.setRealEarthquakeLevel(new BigDecimal(realEarthquakeEntity.getM()));
            simAnaResult.setRealLongitude(new BigDecimal(realEarthquakeEntity.getEpiLon()));
            simAnaResult.setRealLatitude(new BigDecimal(realEarthquakeEntity.getEpiLat()));
            simAnaResult.setRealDepth(realEarthquakeEntity.getEpiDepth());
            simAnaResult.setRealLocation(realEarthquakeEntity.getLocationC());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simAnaResult.setRealTime(sdf.parse(realEarthquakeEntity.getOTime()));
            simAnaResult.setHisPrId(item.getId());
            simAnaResult.setDistanceTarget(f1);
            simAnaResult.setDistance(distance);
            simAnaResult.setSeismicCapacityTarget(f2);
            simAnaResult.setRealHouseTotal(Integer.toString(reaHouTotal));
            simAnaResult.setHouseTotal(Integer.toString(setHouTotal));
            simAnaResult.setRealDearthHouseTotal(Integer.toString(reaHouTotal1));
            simAnaResult.setDearthHouseTotal(Integer.toString(setHouTotal1));
            simAnaResult.setEarthquakeLevelTarget(f3);
            simAnaResult.setSimilarityCalculationResult(simResults);

            simAnaResult.setProvinceName(realEarthquakeEntity.getProvince());
            Integer i = simAnalyseRepository.save(simAnaResult);
            tab = true;
        }
        if (tab) {
            return RestResponse.succeed("1");
        } else {
            return RestResponse.succeed("0");
        }
    }

    private RestResponse realSeismicInfluenceflied(RealEarthquakeEntity item) throws UnsupportedEncodingException {
        String cataId = item.getCataId();
        simAnalyseRepository.delRealSeismicInfluencefliedPbe(cataId);
        simAnalyseRepository.delRealSeismicInfluenceflied(cataId);

        String provinceName = item.getProvince();
        String divisionIds = null;
        IntensityAttenuation defaultModel = null;
        List<IntensityAttenuation> byDivision = null;
        if (item.getCity() != null) {
            //判断省市县的名称是否符合规范
            if ("北京市".equals(provinceName) || "天津市".equals(provinceName) || "重庆市".equals(provinceName) || "上海市".equals(provinceName)) {
                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(provinceName, "utf-8"),
                        URLEncoder.encode(provinceName, "utf-8"), URLEncoder.encode(item.getCity(), "utf-8"));
            } else {
                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(provinceName, "utf-8"),
                        URLEncoder.encode(item.getCity(), "utf-8"), "");
            }
            String[] split1 = divisionIds.split("_");
            byDivision = intensityAttenuationService.getByDivision(split1[0], split1[1], 0);
        } else {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(provinceName, "utf-8"),
                    "", "");
            String[] split1 = divisionIds.split("_");
            byDivision = intensityAttenuationService.getByDivision(split1[0], null, 0);
        }
        if (byDivision == null || byDivision.size() < 1) {
            defaultModel = intensityAttenuationService.getDefaultModel();
        } else {
            defaultModel = byDivision.get(0);
        }
        //地震烈度衰减关系模型
        BigDecimal long_ratio1 = defaultModel.getLongRatio1();
        BigDecimal long_ratio2 = defaultModel.getLongRatio2();
        BigDecimal long_ratio3 = defaultModel.getLongRatio3();
        BigDecimal long_ratio4 = defaultModel.getLongRatio4();
        String long_symbol = defaultModel.getLongSymbol();
        BigDecimal short_ratio1 = defaultModel.getShortRatio1();
        BigDecimal short_ratio2 = defaultModel.getShortRatio2();
        BigDecimal short_ratio3 = defaultModel.getShortRatio3();
        BigDecimal short_ratio4 = defaultModel.getShortRatio4();
        String short_symbol = defaultModel.getShortSymbol();

        BigDecimal formula_ratio1 = defaultModel.getFormulaRatio1();
        BigDecimal formula_ratio2 = defaultModel.getFormulaRatio1();
        //长短轴比例
        BigDecimal scale2 = defaultModel.getScale();

        String faultAngle = setEarthquakeMapService.getClosestFaultageAngleByLonLat(item.getEpiLon(),
                item.getEpiLat());

        boolean isNa = false;
        BigDecimal longX = BigDecimal.ZERO;
        BigDecimal shortY = BigDecimal.ZERO;

        List<RealSeismicInfluenceflied> influenceflyList = new ArrayList<>();

        BigDecimal M = new BigDecimal(item.getM()); //震级
        RealSeismicInfluenceflyPbe seismicInfluenceflyPbe = new RealSeismicInfluenceflyPbe();
        seismicInfluenceflyPbe.setEarthquakeLevel(M);
        isNa = true;
        for (int I = 10; I > 5; I--) {
            RealSeismicInfluenceflied influenceflied = new RealSeismicInfluenceflied();
            influenceflied.setLongitude(new BigDecimal(item.getEpiLon()));
            influenceflied.setLatitude(new BigDecimal(item.getEpiLat()));
            influenceflied.setEarthquakeLevel(M);
            influenceflied.setFaultAngle(new BigDecimal(faultAngle));
            influenceflied.setDzIntensity(String.valueOf(I));

            //长轴：Ia=4.9024+1.3485M-3.9738Lg(Ra+13)
            //式中，Ia、Ib分别为长、短轴烈度，M为震级，Ra、Rb分别为烈度为I时长、短半轴的长度
            //根据公式计算得到Ra、Rb，如果值为负数，则舍掉，为正的则留下

            BigDecimal Ra = BigDecimal.ZERO;//烈度为Ia时长半轴的长度
            double a = (long_ratio1.add(long_ratio2.multiply(M)).subtract(BigDecimal.valueOf(I)))
                    .divide(long_ratio3, 8, RoundingMode.UP).doubleValue();
            if ("ln".equals(long_symbol)) {
                Ra = BigDecimal.valueOf(Math.pow(Math.E, a)).subtract(long_ratio4);
            } else if ("lg".equals(long_symbol)) {
                Ra = BigDecimal.valueOf(Math.pow(10, a)).subtract(long_ratio4);
            }
            if (scale2.compareTo(BigDecimal.ZERO) > 0 && M.compareTo(BigDecimal.valueOf(7)) > -1) {
                // 当使用破裂尺度公式且震级大于等于7.0级时，使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度。
                influenceflied.setDataSource("2");

                //M=5.08+1.16*lg(SRL)
                //M为震级,SRL为破裂尺度
                //根据公式计算得到SRL
                BigDecimal SRL = BigDecimal.valueOf(Math.pow(10, formula_ratio1.subtract(M)
                        .divide(formula_ratio2, 8, RoundingMode.UP).doubleValue()));

                //最终的长轴长度=衰减关系计算的长轴+破裂尺度
                //最终的长轴长度=Ra*2+SRL
                //Ra为烈度为Ia时长半轴的长度,SRL为破裂尺度
                BigDecimal finalRa = Ra.multiply(BigDecimal.valueOf(2)).add(SRL);

                //最终的短轴长度
                BigDecimal finalRb = finalRa.divide(scale2, 2, RoundingMode.HALF_UP);

                if (finalRa.compareTo(BigDecimal.ZERO) < 0) {
                    //finalRa为负数
                    continue;
                }
                if (finalRb.compareTo(BigDecimal.ZERO) < 0) {
                    //finalRb为负数
                    continue;
                }
                finalRa = finalRa.setScale(1, RoundingMode.HALF_UP);//长轴长度
                finalRb = finalRb.setScale(1, RoundingMode.HALF_UP);//短轴长度
                influenceflied.setLongX(finalRa);
                influenceflied.setShortY(finalRb);
            } else {
                // 地震影响场可以使用烈度衰减模型进行模拟，当震级小于7.0级时使用椭圆衰减模型，
                influenceflied.setDataSource("1");

                // 短轴：Ib=4.3517+ 1.2192M-3.7429Lg(Rb+6)
                //式中，Ia、Ib分别为长、短轴烈度，M为震级，Ra、Rb分别为烈度为I时长、短半轴的长度
                //根据公式计算得到Ra、Rb，如果值为负数，则舍掉，为正的则留下

                BigDecimal Rb = BigDecimal.ZERO;//烈度为Ib时短半轴的长度
                double b = (short_ratio1.add(short_ratio2.multiply(M)).subtract(BigDecimal.valueOf(I))).divide(short_ratio3, 8, RoundingMode.UP).doubleValue();
                if ("lg".equals(short_symbol)) {
                    Rb = BigDecimal.valueOf(Math.pow(10, b)).subtract(short_ratio4);
                } else if ("ln".equals(short_symbol)) {
                    Rb = BigDecimal.valueOf(Math.pow(Math.E, b)).subtract(short_ratio4);
                }
                if (Ra.compareTo(BigDecimal.ZERO) < 0) {
                    //Ra为负数
                    continue;
                }
                if (Rb.compareTo(BigDecimal.ZERO) < 0) {
                    //Rb为负数
                    continue;
                }
                Ra = Ra.multiply(BigDecimal.valueOf(2)).setScale(1, RoundingMode.HALF_UP);//长轴长度
                Rb = Rb.multiply(BigDecimal.valueOf(2)).setScale(1, RoundingMode.HALF_UP);//短轴长度
                influenceflied.setLongX(Ra);
                influenceflied.setShortY(Rb);
            }
            influenceflied.setUuid(UUIDGenerator.getUUID());

            String influenceEllipse = null;
            if (!isNa) {
                //环
                influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(item.getEpiLon(),
                        item.getEpiLat(), influenceflied.getLongX().toString(),
                        influenceflied.getShortY().toString(),
                        String.valueOf(faultAngle), longX.toString(), shortY.toString());
            } else {
                //椭圆
                influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(item.getEpiLon(),
                        item.getEpiLat(), influenceflied.getLongX().toString(),
                        influenceflied.getShortY().toString(),
                        String.valueOf(faultAngle), null, null);
            }
            isNa = false;
            longX = influenceflied.getLongX();
            shortY = influenceflied.getShortY();
            influenceflied.setGeom(influenceEllipse);
            //处理空间数据，判断存在自相交则获取修复后的空间数据，否则返回原空间数据wkt
            //String geomText = taskRegionMapService.getGeomValidWkt(influenceEllipse);
            //influenceflied.setGeom("ST_GeometryFromText('" + geomText + "',4490)");

            influenceflied.setCataId(cataId);
            influenceflyList.add(influenceflied);
            //settingSeismicInfluencefliedRepository.saveSettingSeismicInfluenceflied(influenceflied);
            if (I == 6) {
                seismicInfluenceflyPbe.setUuid(UUIDGenerator.getUUID());
                seismicInfluenceflyPbe.setDzIntensity(String.valueOf(I));
                seismicInfluenceflyPbe.setLongX(influenceflied.getLongX());
                seismicInfluenceflyPbe.setShortY(influenceflied.getShortY());
                seismicInfluenceflyPbe.setDataSource("1");
                //椭圆
                influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(item.getEpiLon(),
                        item.getEpiLat(), influenceflied.getLongX().toString(),
                        influenceflied.getShortY().toString(), faultAngle, null, null);
                seismicInfluenceflyPbe.setGeom(influenceEllipse);
                seismicInfluenceflyPbe.setCataId(item.getCataId());
                simAnalyseRepository.saveRealSeismicInfluenceflied(seismicInfluenceflyPbe);
            }
        }
        if (influenceflyList.size() > 0){
            //批量插入
            simAnalyseRepository.saveinfluenceflyList(influenceflyList);
        }

        return RestResponse.succeed(seismicInfluenceflyPbe);
    }

    private SeismicInfluenceflyPbe settingSeismicInfluenceflied(SettingSeismicDetails details) throws UnsupportedEncodingException {
        String id = details.getId();

        String[] split = details.getMacroPosition().split(",");
        String divisionIds = null;
        //判断省市县的名称是否符合规范
        if ("北京市".equals(split[0]) || "天津市".equals(split[0]) || "重庆市".equals(split[0]) || "上海市".equals(split[0])) {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(split[0], "utf-8"),
                    URLEncoder.encode(split[1], "utf-8"), URLEncoder.encode(split[2], "utf-8"));
        } else {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(split[0], "utf-8"),
                    URLEncoder.encode(split[1], "utf-8"), "");
        }
        String[] split1 = divisionIds.split("_");
        List<IntensityAttenuation> byDivision = intensityAttenuationService.getByDivision(split1[0], split1[1], 0);
        IntensityAttenuation defaultModel = null;
        if (byDivision == null || byDivision.size() < 1) {
            defaultModel = intensityAttenuationService.getDefaultModelByModelName("系统默认地震烈度衰减模型2");
        } else {
            defaultModel = byDivision.get(0);
        }
        //地震烈度衰减关系模型
        BigDecimal long_ratio1 = defaultModel.getLongRatio1();
        BigDecimal long_ratio2 = defaultModel.getLongRatio2();
        BigDecimal long_ratio3 = defaultModel.getLongRatio3();
        BigDecimal long_ratio4 = defaultModel.getLongRatio4();
        String long_symbol = defaultModel.getLongSymbol();
        BigDecimal short_ratio1 = defaultModel.getShortRatio1();
        BigDecimal short_ratio2 = defaultModel.getShortRatio2();
        BigDecimal short_ratio3 = defaultModel.getShortRatio3();
        BigDecimal short_ratio4 = defaultModel.getShortRatio4();
        String short_symbol = defaultModel.getShortSymbol();

        BigDecimal formula_ratio1 = defaultModel.getFormulaRatio1();
        BigDecimal formula_ratio2 = defaultModel.getFormulaRatio1();
        //长短轴比例
        BigDecimal scale2 = defaultModel.getScale();

        String faultAngle = setEarthquakeMapService.getClosestFaultageAngleByLonLat(details.getLongitude().toString(),
                details.getLatitude().toString());

        BigDecimal M = details.getEarthquakeLevel(); //震级
        SeismicInfluenceflyPbe influenceflied = new SeismicInfluenceflyPbe();
        int I = 6;
        //长轴：Ia=4.9024+1.3485M-3.9738Lg(Ra+13)
        //式中，Ia、Ib分别为长、短轴烈度，M为震级，Ra、Rb分别为烈度为I时长、短半轴的长度
        //根据公式计算得到Ra、Rb，如果值为负数，则舍掉，为正的则留下
        BigDecimal longX = BigDecimal.ZERO;
        BigDecimal shortY = BigDecimal.ZERO;

        double a = (long_ratio1.add(long_ratio2.multiply(M)).subtract(BigDecimal.valueOf(I)))
                .divide(long_ratio3, 8, RoundingMode.UP).doubleValue();
        if ("ln".equals(long_symbol)) {
            longX = BigDecimal.valueOf(Math.pow(Math.E, a)).subtract(long_ratio4);
        } else if ("lg".equals(long_symbol)) {
            longX = BigDecimal.valueOf(Math.pow(10, a)).subtract(long_ratio4);
        }
        if (scale2.compareTo(BigDecimal.ZERO) > 0 && M.compareTo(BigDecimal.valueOf(7)) > -1) {
            // 当使用破裂尺度公式且震级大于等于7.0级时，使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度。

            //M=5.08+1.16*lg(SRL)
            //M为震级,SRL为破裂尺度
            //根据公式计算得到SRL
            BigDecimal SRL = BigDecimal.valueOf(Math.pow(10, formula_ratio1.subtract(M)
                    .divide(formula_ratio2, 8, RoundingMode.UP).doubleValue()));

            //最终的长轴长度=衰减关系计算的长轴+破裂尺度
            //最终的长轴长度=Ra*2+SRL
            //Ra为烈度为Ia时长半轴的长度,SRL为破裂尺度
            longX = longX.multiply(BigDecimal.valueOf(2)).add(SRL);

            //最终的短轴长度
            shortY = longX.divide(scale2, 2, RoundingMode.HALF_UP);

            if (longX.compareTo(BigDecimal.ZERO) < 0) {
                //finalRa为负数
                return null;
            }
            if (shortY.compareTo(BigDecimal.ZERO) < 0) {
                //finalRb为负数
                return null;
            }
            longX = longX.setScale(1, RoundingMode.HALF_UP);//长轴长度
            shortY = shortY.setScale(1, RoundingMode.HALF_UP);//短轴长度
        } else {
            // 地震影响场可以使用烈度衰减模型进行模拟，当震级小于7.0级时使用椭圆衰减模型，

            // 短轴：Ib=4.3517+ 1.2192M-3.7429Lg(Rb+6)
            //式中，Ia、Ib分别为长、短轴烈度，M为震级，Ra、Rb分别为烈度为I时长、短半轴的长度
            //根据公式计算得到Ra、Rb，如果值为负数，则舍掉，为正的则留下

            shortY = BigDecimal.ZERO;//烈度为Ib时短半轴的长度
            double b = (short_ratio1.add(short_ratio2.multiply(M)).subtract(BigDecimal.valueOf(I))).divide(short_ratio3, 8, RoundingMode.UP).doubleValue();
            if ("lg".equals(short_symbol)) {
                shortY = BigDecimal.valueOf(Math.pow(10, b)).subtract(short_ratio4);
            } else if ("ln".equals(short_symbol)) {
                shortY = BigDecimal.valueOf(Math.pow(Math.E, b)).subtract(short_ratio4);
            }
            if (longX.compareTo(BigDecimal.ZERO) < 0) {
                //finalRa为负数
                return null;
            }
            if (shortY.compareTo(BigDecimal.ZERO) < 0) {
                //finalRb为负数
                return null;
            }
            longX = longX.multiply(BigDecimal.valueOf(2)).setScale(1, RoundingMode.HALF_UP);//长轴长度
            shortY = shortY.multiply(BigDecimal.valueOf(2)).setScale(1, RoundingMode.HALF_UP);//短轴长度
        }
        influenceflied.setDetailsId(id);

        //椭圆
        String influenceEllipse = setEarthquakeMapService.createInfluenceEllipse(details.getLongitude().toString(),
                details.getLatitude().toString(), longX.toString(),
                shortY.toString(),
                String.valueOf(faultAngle), null, null);
        influenceflied.setGeom(influenceEllipse);
        return influenceflied;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean save(BigDecimal kilometre, String m, RealEarthquakeEntity realEarthquakeEntity) throws ParseException {
        JSONArray jsonArray = new JSONArray();
        BigDecimal epiLon = new BigDecimal(realEarthquakeEntity.getEpiLon());
        BigDecimal epiLat = new BigDecimal(realEarthquakeEntity.getEpiLat());
        MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzdzzh");
        headers.set("subsystemCode", "dzdzzhpg");
        HttpEntity<MultiValueMap> r = new HttpEntity<>(valueMap, headers);
        try {
            String url =
                    basicDataUrl1 + "/datacenter/jcEarthquakeDamageSurvey/ypg/getEventList?epiLon="+epiLon+"&epiLat="+epiLat+"&kilometre="+kilometre+"&m="+m;
            JSONObject body = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody();
            if (body != null) {
                jsonArray = body.getJSONArray("data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (jsonArray==null||jsonArray.size()<1){
            return false;
        }
        List<String> attachIds = attachmentInfoService.getAttachId();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            BigDecimal setLon = jsonObject.getBigDecimal("jedsLongitude");
            BigDecimal setLat = jsonObject.getBigDecimal("jedsLatitude");
            Double realLon = new Double(realEarthquakeEntity.getEpiLon());
            Double realLat = new Double(realEarthquakeEntity.getEpiLat());
            String distance = DistanceUtils.getDistance(setLon.doubleValue(), setLat.doubleValue(), realLon, realLat);
            HisEarDamResult hisEarDamResult = JSON.parseObject(jsonObject.toJSONString(),HisEarDamResult.class);
            hisEarDamResult.setId(UUIDGenerator.getUUID());
            hisEarDamResult.setRealEarthquakeLevel(new BigDecimal(realEarthquakeEntity.getM()));
            hisEarDamResult.setRealLongitude(new BigDecimal(realEarthquakeEntity.getEpiLon()));
            hisEarDamResult.setRealLatitude(new BigDecimal(realEarthquakeEntity.getEpiLat()));
            hisEarDamResult.setRealDepth(realEarthquakeEntity.getEpiDepth());
            hisEarDamResult.setRealLocation(realEarthquakeEntity.getLocationC());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            hisEarDamResult.setRealTime(sdf.parse(realEarthquakeEntity.getOTime()));
            hisEarDamResult.setDistance(new BigDecimal(distance));
            // hisEarDamResult.setJedsId(jsonObject.getString("jedsId"));
            // BeanUtils.copyProperties(jsonObject, hisEarDamResult);
            //等震线图片
            JSONArray isolinePicList = jsonObject.getJSONArray("isolinePicList");
            if (isolinePicList != null) {
                for (int j=0;j<isolinePicList.size();j++){
                    JSONObject isolinePic = isolinePicList.getJSONObject(j);
                    String isolinePic1 = isolinePic.getString("isolinePic");
                    if (PlatformObjectUtils.isNotEmpty(isolinePic1)) {
                        String[] id = isolinePic1.split(",");
                        for (int k = 0; k < id.length; k++) {
                            if (!attachIds.contains(id[k])) {
                                attachmentInfoService.saveOne(JSON.parseObject(isolinePic.toString(),
                                        AttachmentInfoEntity.class));
                            }
                        }
                    }
                }
            }
            //烈度图图片
            JSONArray intensityMapList = jsonObject.getJSONArray("intensityMapList");
            if (intensityMapList != null) {
                for (int j=0;j<intensityMapList.size();j++){
                    JSONObject intensityMap = intensityMapList.getJSONObject(j);
                    String intensityMap1 = intensityMap.getString("intensityMap");
                    if (PlatformObjectUtils.isNotEmpty(intensityMap1)) {
                        String[] id = intensityMap1.split(",");
                        for (int k = 0; k < id.length; k++) {
                            if (!attachIds.contains(id[k])) {
                                attachmentInfoService.saveOne(JSON.parseObject(intensityMap.toString(),
                                        AttachmentInfoEntity.class));
                            }
                        }
                    }
                }
            }
            //典型震害照片
            JSONArray jedsZhzpList = jsonObject.getJSONArray("jedsZhzpList");
            if (jedsZhzpList != null) {
                for (int j=0;j<jedsZhzpList.size();j++){
                    JSONObject jedsZhzp = jedsZhzpList.getJSONObject(j);
                    String jedsZhzp1 = jedsZhzp.getString("jedsZhzp");
                    if (PlatformObjectUtils.isNotEmpty(jedsZhzp1)) {
                        String[] id = jedsZhzp1.split(",");
                        for (int k = 0; k < id.length; k++) {
                            if (!attachIds.contains(id[k])) {
                                attachmentInfoService.saveOne(JSON.parseObject(jedsZhzp.toString(),
                                        AttachmentInfoEntity.class));
                            }
                        }
                    }
                }
            }
            //附件列表
            JSONArray attachmentList = jsonObject.getJSONArray("attachmentList");
            if (attachmentList != null) {
                for (int j=0;j<attachmentList.size();j++){
                    JSONObject attachment = attachmentList.getJSONObject(j);
                    String attachment1 = attachment.getString("attachment");
                    if (PlatformObjectUtils.isNotEmpty(attachment1)) {
                        String[] id = attachment1.split(",");
                        for (int k = 0; k < id.length; k++) {
                            if (!attachIds.contains(id[k])) {
                                attachmentInfoService.saveOne(JSON.parseObject(attachment.toString(),
                                        AttachmentInfoEntity.class));
                            }
                        }
                    }
                }
            }

            hisEarDamResult.setRealProvince(realEarthquakeEntity.getProvince());
            List<String> provinceInfo = setEarthquakeMapService.queryProvinceByLonLat(setLon.toString(), setLat.toString());
            String provinceName = "";
            if (!(provinceInfo.size() <= 0)) {
                provinceName = provinceInfo.get(1);
            }
            hisEarDamResult.setProvince(provinceName);
            hisEarDamResultRepository.save(hisEarDamResult);
            // RealEqDisaster realEqDisaster = JSON.parseObject(jsonObject.toJSONString(),RealEqDisaster.class);
            // realEqDisaster.setRedId(UUIDGenerator.getUUID());
            // simAnalyseRepository.saveRealEqDisaster(realEqDisaster);
        }

        return true;
    }

    @Override
    public Map<String, Object> getPage(QueParams1 queParams, int curPage, int pageSize) {
        Map<String, Object> page = simAnalyseRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public Map<String, Object> fingById(String id) {
        Map<String, Object> map = new HashMap<>();
        SimAnaResult simAnaResult = simAnalyseRepository.fingById(id);
        ParamSettingVO paramSetting = paramSettingService.getParamSetting();
        HisPrEntity hisPrEntity = hisprService.getDateById(simAnaResult.getHisPrId());
        PreAssessTaskEntity preAssessTask = preAssessTaskService.getPreAssessTaskByTaskNum(hisPrEntity.getDhpTaskNum());
        if (PlatformObjectUtils.isNotEmpty(preAssessTask)){
            ReportManagement report = reportManagementService.getReportByTaskId(preAssessTask.getId());
            map.put("report", report);
        }else {
            map.put("report", null);
        }
        map.put("simAnaResult", simAnaResult);
        map.put("paramSetting", paramSetting);
        map.put("hisPrEntity", hisPrEntity);
        map.put("task", preAssessTask);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse similitudeAnalyse1Test() {
        String cataId = "";
        try {
            //调取接口 返回真实数据对象
            //List<RealEarthquakeEntity> realEarthquakeEntities = Xml2ObjectUtil.getRealEarthquakeEntity(URL);
            List<RealEarthquakeEntity> realEarthquakeEntities = new ArrayList<>();
            RealEarthquakeEntity testEntity = new RealEarthquakeEntity();
            testEntity.setCataId("CC20230806023360.00");
            testEntity.setAutoFlag("M");
            testEntity.setOTime("2023-08-06 02:33:59");
            testEntity.setLocationC("山东德州市平原县");
            testEntity.setM("5.5");
            testEntity.setEpiLat("37.16");
            testEntity.setEpiLon("116.34");
            testEntity.setEpiDepth("10");
            realEarthquakeEntities.add(testEntity);

            if (realEarthquakeEntities == null || realEarthquakeEntities.size() == 0) {
                return RestResponse.fail("=====该时间:{}" + PlatformDateUtils.getCurrentTimestamp() + "的数据为空");
            }
            List<RealEarthquakeEntity> collect = realEarthquakeEntities.stream().sorted(Comparator.comparing(RealEarthquakeEntity::getOTime,
                    Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());
            RealEarthquakeEntity item = collect.get(collect.size() - 1);

            cataId = item.getCataId();
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(cataId))) {
                return RestResponse.fail("该线程中的该数据:{}" + cataId + "正在被计算！");
            }
            redisTemplate.opsForValue().set(cataId, "1", 10L, TimeUnit.SECONDS);

            RealEarthquakeEntity realEarthquakeEntity = simAnalyseRepository.getById(cataId);
            if (realEarthquakeEntity != null) {
                return RestResponse.fail("该数据:{}" + cataId + "已经被计算！");
            }

            String s = setEarthquakeMapService.queryProvinceCityCountyNameStringByLonLat(item.getEpiLon(), item.getEpiLat());
            if (PlatformObjectUtils.isEmpty(s)) {
                return RestResponse.fail("未获取到当前数据:{}" + cataId + "经纬度的省份！");
            }
            String[] split = s.split(",");
            //省名称
            item.setProvince(split[0]);
            //市名称
            item.setCity(split[1]);
            //县名称
            item.setCounty(split[2]);
            simAnalyseRepository.saveRealEarthquake(item);

            String provinceName = split[0];
            //判断是否是东部
            boolean eastFlag = ListUtil.useList(AreaConsts.EAST, provinceName);
            //判断是否是西部
            boolean westFlag = ListUtil.useList(AreaConsts.WEST, provinceName);
            //获取计算参数
            ParamSettingVO params = paramSettingService.getParamSetting();
            //是东部   判断震级是否大于4
            //是西部   判断震级是否大于5
            if ((eastFlag && AreaConsts.compare(new Double(item.getM()), AreaConsts.EAST_MAGNITUDE)) || (westFlag && AreaConsts.compare(new Double(item.getM()), AreaConsts.WEST_MAGNITUD))) {
                //震后辅助决策
                auxiliaryDecisionService.writeData(item);

                //历史预评估结果数据
                //获取实际发生地震震中位置所在区县有设定地震的或在O（默认50）公里范围内有设定地震的数据
                List<HisPrEntity> list1 = hisprService.getDataByLongitudeAndLatitude(item.getEpiLon(),
                        item.getEpiLat(), new BigDecimal(params.getO()).multiply(BigDecimal.valueOf(1000)), item.getM());
                // List<SetSeiPointVo> setSeiPointVoList = settingSeismicService.getDataByLongitudeAndLatitude(item.getEpiLon(), item.getEpiLat(), params.getO(), item.getM());
                //筛选出震级差 |设定地震震级-实际地震震级|<=0.3的数据并去重
                // List<HisPrEntity> newList = dataWinnow(list1, new BigDecimal(item.getM()));
                if (list1 != null && list1.size()>0){
                    RestResponse restResponse = similarityAnalysis1(item, list1, params);
                    if (restResponse.getCode() != 200) {
                        return RestResponse.fail(restResponse.getMessage());
                    }
                }

                //历史地震灾害数据
                boolean boo = save(new BigDecimal(params.getU()).multiply(BigDecimal.valueOf(1000)), item.getM(), item);
                if (!boo){
                    simAnalyseRepository.delRealEarthquake(cataId);
                    return RestResponse.fail("历史地震灾害数据保存失败！");
                }

            } else {
                return RestResponse.fail("当前数据:{}" + cataId + "未满足震级大于等于东部地区4级、西部地区5级！");
            }
            // List<KangZhenTu> byGeom = kangZhenTuService.getByGeom(influenceEllipse);
        } catch (Exception e) {
            e.printStackTrace();
            simAnalyseRepository.delRealEarthquake(cataId);
            return RestResponse.fail("分析并保存失败！");
        } finally {
            if (PlatformObjectUtils.isNotEmpty(cataId)) {
                redisTemplate.delete(cataId);
            }
        }
        return RestResponse.succeed("分析并保存成功！");
    }

    @Override
    public String getNewestSimAnaResultId() {
        return simAnalyseRepository.getNewestSimAnaResultId();
    }
}
